/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.langage.commande.serveur.message.cor;

import com.desanonymerUtilisateurs.ConnectDatabase;
import com.lloseng.ocsf.server.AbstractServer;
import com.lloseng.ocsf.server.ConnectionToClient;
import com.lloseng.ocsf.simplechat.phase1.server.EchoServer;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Touf
 */
public class AnalyseurLogin extends AbstractAnalyseurClientMessage {

    public AnalyseurLogin(AbstractAnalyseurClientMessage suivant, AbstractServer server) {
        super(suivant, server);
    }

    @Override
    protected boolean analyseCommande(String chaine, ConnectionToClient client) {
        if (chaine.trim().toLowerCase().startsWith("#login")) {
            String msgToClient = null;
            boolean needToCloseConnection = false;

            String[] args = chaine.split(" ");
            if (args.length != 3) {
                needToCloseConnection = true;
                msgToClient = "Argument manquant.";
            } else {


                String id = args[1];
                String password = args[2];
                if (id == null || id.isEmpty()) {
                    needToCloseConnection = true;
                    msgToClient = "Pas d'identifiant fourni. La connection va etre interrompue.";
                } else if (client.getInfo("id") == null) {
                    ConnectDatabase connect = new ConnectDatabase();
                    connect.connectDatabase();
                    System.out.println(id);

                    ResultSet result = connect.doRequest("SELECT password FROM `user` WHERE userName='" + id + "';");
                    try {
                        connect.verifPassword(result, id);
                        client.setInfo("id", id);
                        msgToClient = "Vous etes connecte sur le serveur " + this.server.getPort();
                    } catch (Exception e) {
                        needToCloseConnection = true;
                        msgToClient = e.getMessage();
                    }


                } else {
                    msgToClient = "Vous etiez déja connecte";
                }
            }
            try {
                client.sendToClient(msgToClient);
                if (needToCloseConnection) {
                    client.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(AnalyseurLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
            return true;
        }
        return false;
    }
}
